#include "M3gView.hpp"
#include "Scene.hpp"
#include "CameraController.hpp"
#include "constants.hpp"
#include <m3g/m3g.hpp>
#include <GL/gl.h>
#include <GL/glu.h>
#include <vector>
#include <iostream>
using namespace m3g;
using namespace std;
using namespace m3g_viewer;

const char* M3G_FILE_NAME = "simple.m3g";


M3gView:: M3gView (MainView* view) : Fl_Gl_Window(M3G_VIEW_X,
                                                  M3G_VIEW_Y,
                                                  M3G_VIEW_WIDTH,
                                                  M3G_VIEW_HEIGHT),
                                                  main_view(view), scene(0), camera_controller(0)
{
    scene             = new Scene ();
    camera_controller = new CameraController ();
}



M3gView:: ~M3gView ()
{

}



void M3gView:: init ()
{
    
}

void M3gView:: draw ()
{
    if (!valid()) {
        init();
    }

    scene->render ();

}

int M3gView:: handle (int event)
{
    switch (event) {
    case FL_PUSH:
    case FL_RELEASE:
    case FL_DRAG:
    case FL_MOUSEWHEEL:
        cout << "MOUSE IVENT\n";
        break;
    default:
        break;
    }

    return Fl_Gl_Window::handle(event);   // (*1)

}

void M3gView:: handle_mouse_event (int event)
{
    int x0  = mouse_x;
    int y0  = mouse_y;
    mouse_x = Fl::event_x();
    mouse_y = Fl::event_y();
    int dx  = mouse_x - x0;
    int dy  = mouse_y - y0;
    int btn = Fl::event_button();

    switch (btn) {
    case FL_RIGHT_MOUSE: {
        if (dx > 0)
            camera_controller->turn_right();
        else if (dx < 0)
            camera_controller->turn_left();
        if (dy > 0)
            camera_controller->turn_down();
        else if (dy < 0)
            camera_controller->turn_up();
        break;
    }
    case FL_LEFT_MOUSE: {
        break;
    }
    case FL_MIDDLE_MOUSE: {
        if (dx > 0)
            camera_controller->move_right();
        else if (dx < 0)
            camera_controller->move_left();
        if (dy > 0)
            camera_controller->move_down();
        else if (dy < 0)
            camera_controller->move_up();
        break;
    }
    case 4: {   // ホイールの上回転
        camera_controller->move_forward();
        break;
    }
    case 5: {  // ホイールの下回転
        camera_controller->move_back();
        break;
    }
    default:
        break;
    }

    
}


void M3gView:: load (const char* name)
{
    scene->load (name);
    camera_controller->set_camera (scene->get_camera());
}

CameraController* M3gView:: get_camera_controller ()
{
    return camera_controller;
}

Scene* M3gView:: get_scene ()
{
    return scene;
}


